package com.cursordemo.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.cursordemo.config.OssConfig;
import com.cursordemo.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传服务实现类
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    
    @Autowired
    private OSS ossClient;
    
    @Autowired
    private OssConfig ossConfig;
    
    @Override
    public String uploadFile(MultipartFile file) {
        try {
            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 生成文件名：时间戳 + UUID + 扩展名
            String fileName = generateFileName(extension);
            
            // 上传文件到OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(), 
                fileName, 
                file.getInputStream()
            );
            
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            
            // 生成文件访问URL
            String fileUrl = "https://" + ossConfig.getBucketName() + "." + 
                           ossConfig.getEndpoint().replace("https://", "") + "/" + fileName;
            
            log.info("文件上传成功 - 文件名: {}, URL: {}", fileName, fileUrl);
            
            return fileUrl;
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成唯一文件名
     * @param extension 文件扩展名
     * @return 文件名
     */
    private String generateFileName(String extension) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        return timestamp + "_" + uuid + extension;
    }
}

